package com.infolab.aims.web.taglib;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.infolab.aims.common.CommonUtil;
import com.infolab.aims.common.bean.SearchCriteria;

public class SortTag  extends BodyTagSupport {
	
	private Log logger = LogFactory.getLog(getClass());
	
	private String columnName;
	private String label;
	
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		String url = (String) pageContext.getAttribute("paginationUrl");
		
		Enumeration en = pageContext.getRequest().getAttributeNames();
		SearchCriteria searchCriteria = null ;
		while(en.hasMoreElements())
		{
			String attrName = (String) en.nextElement();
			Object o = pageContext.getAttribute(attrName,PageContext.SESSION_SCOPE);
			if(o instanceof SearchCriteria)
			{
				searchCriteria	= (SearchCriteria) o;
				break;
			}
		}
		String sortName = searchCriteria.getSortName();
		String sortType = searchCriteria.getSortType();
		String ascUrl = url+"?sortType=asc&sortName="+columnName;
		String descUrl = url+"?sortType=desc&sortName="+columnName;
		try {
			if(StringUtils.equalsIgnoreCase(sortName, columnName))
			{
				if(StringUtils.equalsIgnoreCase(sortType, "asc"))
					out.write("<span class='left'>"+label+"</span> <a href='"+descUrl+"' title='Descending'><span class='ui-icon ui-icon-triangle-1-s left'></span></a>");
				else
					out.write("<span class='left'>"+label+"</span> <a href='"+ascUrl+"' title='Ascending'><span class='ui-icon ui-icon-triangle-1-n left'></span></a>");
			}
			else
				out.write("<span class='left'>"+label+"</span> <a href='"+ascUrl+"' title='Ascending'><span class='ui-icon ui-icon-triangle-1-n left'></span></a>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(CommonUtil.getStackTrace(e));
		}
		return EVAL_BODY_INCLUDE;
	}

	public String getColumnName() {
		return columnName;
	}

	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}
	}
